﻿namespace Ops.Host.Core.Services;

internal sealed class NoticeService : ScadaDomainService, INoticeService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger _logger;

    private const string PLC_Notice_Energy_1 = nameof(PLC_Notice_Energy_1); // 能耗（有功）
    private const string PLC_Notice_Energy_2 = nameof(PLC_Notice_Energy_2); // 能耗（无功）

    public NoticeService(IServiceProvider serviceProvider, ILogger<NoticeService> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task HandleAsync(ForwardData data)
    {
        // 能耗
        if (data.Tag is PLC_Notice_Energy_1 or PLC_Notice_Energy_2)
        {
            await HandleEnergyConsumeAsync(data);
            return;
        }
    }

    private async Task HandleEnergyConsumeAsync(ForwardData data)
    {
        try
        {
            var energy = data.Self().GetReal();
            var energy0 = Math.Round(Convert.ToDecimal(energy), 2);
            var category = data.Self().Name ?? "";
            DvEnergyConsume item = new()
            {
                LineCode = data.Schema.Line,
                StationCode = data.Schema.Station,
                Category = category,
                Value = energy0,
            };

            using var scope = _serviceProvider.CreateScope();
            var energyConsumeService = scope.ServiceProvider.GetRequiredService<IDvEnergyConsumeService>();
            await energyConsumeService.AddEnergyConsumeAsync(item);

            // 推送消息
            await MessageTaskQueueManager.Default.QueueAsync(new Message(item.LineCode, item.StationCode, MessageClassify.Energy, category, energy0));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"[NoticeService] 能耗记录信息异常，Tag：{data.Tag}");
        }
    }
}
